import React from 'react';
import {
  StyleSheet,
  View,
  TouchableOpacity,
} from 'react-native';
import {
  Toast
} from 'antd-mobile-rn';
import InputItem from '../InputItem';
import FontText from '../FontText';
import Switch from '../Switch';
import { scaleSize } from '../../../utils/screen';
import { i18n } from '../../../i18n';
import _ from 'lodash';

class EmployeeModal extends React.Component {
  constructor(props) {
    super(props);

    const { employee } = props;

    this.state = {
      employee,
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.employee !== nextProps.employee) {
      this.setState({
        employee: nextProps.employee,
      });
    }
  }

  validateEmail(email) {
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
  }

  validatePincode(pincode) {
    var re = /^[0-9]{6}$/;
    return re.test(pincode);
  }

  validateEmployeeSavingData(employee, onSuccess, onFail) {
    let error = {};

    const requiredRules = [
      {
        key: 'name',
        condition: (data) => (data && (data.length !== 0)),
        message: i18n.t('employees.modal.employee.required.name'),
      },
      {
        key: 'mobile',
        condition: (data) => (data && (data.length !== 0)),
        message: i18n.t('employees.modal.employee.required.mobile'),
      },
      {
        key: 'email',
        condition: (data) => (data && (data.length !== 0) && this.validateEmail(data)),
        message: i18n.t('employees.modal.employee.required.email'),
      },
      {
        key: 'pincode',
        condition: (data) => (data && (data.length !== 0) && this.validatePincode(data)),
        message: i18n.t('employees.modal.employee.required.pincode'),
      },
    ];

    for (let rule of requiredRules) {
      const { key, condition, message } = rule;
      if (!condition(employee[key])) {
        error = {
          message
        };
        break;
      }
    }

    if (!_.isEmpty(error)) {
      onFail && onFail(error);
    } else {
      onSuccess && onSuccess();
    }
  }

  onSave() {
    const { employee } = this.state;
    const { onSave } = this.props;

    this.validateEmployeeSavingData(
      employee,
      () => onSave && onSave(employee),
      (error) => Toast.info(error.message, 3, null, false),
    );
  }

  onCancel() {
    const { onCancel } = this.props;

    onCancel && onCancel();
  }

  changeUserNo(user_no) {
    this.setState({
      employee: {
        ...this.state.employee,
        user_no,
      },
    });
  }

  changeStatus(status) {
    this.setState({
      employee: {
        ...this.state.employee,
        status,
      },
    });
  }

  changeName(name) {
    this.setState({
      employee: {
        ...this.state.employee,
        name,
      },
    });
  }

  changeMobile(mobile) {
    this.setState({
      employee: {
        ...this.state.employee,
        mobile,
      },
    });
  }

  changeNote(note) {
    this.setState({
      employee: {
        ...this.state.employee,
        note,
      },
    });
  }

  changeEmail(email) {
    this.setState({
      employee: {
        ...this.state.employee,
        email,
      },
    });
  }

  changePincode(pincode) {
    this.setState({
      employee: {
        ...this.state.employee,
        pincode,
      },
    });
  }

  render() {
    const { show } = this.props;

    if (show) {
      return this._renderModal();
    }

    return null;
  }

  _renderModal() {
    const { employee } = this.state;
    const isEditing = employee.user_id.length !== 0;

    return (
      <View style={styles.modalView}>
        <View style={styles.modalContainer}>
          <View style={styles.modalHeader}>
            <TouchableOpacity
              style={styles.modalHeaderButton}
              activeOpacity={0.8}
              onPress={() => this.onCancel()}
            >
              <FontText
                style={styles.modalHeaderButtonLabel}
                font={'book'}
              >
                {i18n.t('btns.cancel')}
              </FontText>
            </TouchableOpacity>
            <FontText
              style={styles.modalHeaderTitle}
              font={'medium'}
            >
              {
                isEditing ?
                i18n.t('employees.modal.employee.editemployee') :
                i18n.t('employees.modal.employee.newemployee')
              }
            </FontText>
            <TouchableOpacity
              style={styles.modalHeaderButton}
              activeOpacity={0.8}
              onPress={() => this.onSave()}
            >
              <FontText
                style={styles.modalHeaderButtonLabel}
                font={'book'}
              >
                {i18n.t('btns.save')}
              </FontText>
            </TouchableOpacity>
          </View>
          <View style={styles.modalBody}>
            <View style={styles.formGroup}>
              <View style={styles.formControl}>
                <View style={styles.inlineFormGroup}>
                  <FontText
                    font={'book'}
                    height={scaleSize(50)}
                    style={styles.formLabelText}
                  >
                    {i18n.t('employees.modal.employee.field.user_no.label')}
                  </FontText>
                  <InputItem
                    value={employee.user_no || ''}
                    valuChange={(val) => this.changeUserNo(val)}
                    style={[styles.formControlText, { textAlign: 'right' }]}
                    placeholder={i18n.t('employees.modal.employee.field.user_no.placeholder')}
                    keyboardType='number-pad'
                  />
                </View>
              </View>
              <View style={[styles.formControl, { backgroundColor: 'whitesmoke'}]}>
                <View style={styles.inlineFormGroup}>
                  <FontText
                    font={'book'}
                    height={scaleSize(50)}
                    style={styles.formLabelText}
                  >
                    {i18n.t('employees.modal.employee.field.status.label')}
                  </FontText>
                   <Switch
                    checked={parseInt(employee.status, 10) === 1 ? true : false}
                    onPress={(checked) => this.changeStatus(checked ? 1 : 0)}
                    height={scaleSize(50)}
                    activeColor='steelblue'
                  >
                  </Switch>
                </View>
              </View>
            </View>
            <View style={styles.formGroup}>
              <View style={styles.formControl}>
                <InputItem
                  value={employee.name || ''}
                  valuChange={(val) => this.changeName(val)}
                  style={styles.formControlText}
                  placeholder={i18n.t('employees.modal.employee.field.name.placeholder')}
                />
              </View>
              <View style={styles.formControl}>
                <InputItem
                  value={employee.mobile || ''}
                  valuChange={(val) => this.changeMobile(val)}
                  style={styles.formControlText}
                  placeholder={i18n.t('employees.modal.employee.field.mobile.placeholder')}
                  keyboardType='number-pad'
                />
              </View>
            </View>
            <View style={styles.formGroup}>
              <View style={styles.formControl}>
                <InputItem
                  value={employee.email || ''}
                  valuChange={(val) => this.changeEmail(val)}
                  style={styles.formControlText}
                  placeholder={i18n.t('employees.modal.employee.field.email.placeholder')}
                  keyboardType='email-address'
                />
              </View>
              <View style={styles.formControl}>
                <View style={styles.inlineFormGroup}>
                  <FontText
                    font={'book'}
                    height={scaleSize(50)}
                    style={styles.formLabelText}
                  >
                    {i18n.t('employees.modal.employee.field.pincode.label')}
                  </FontText>
                  <InputItem
                    value={employee.pincode || ''}
                    valuChange={(val) => this.changePincode(val)}
                    style={[styles.formControlText, { textAlign: 'right' }]}
                    keyboardType='number-pad'
                    maxLength={6}
                    secureTextEntry={true}
                    placeholder={i18n.t('employees.modal.employee.field.pincode.placeholder')}
                  />
                </View>
              </View>
            </View>
            <View style={styles.formGroup}>
              <View style={styles.formControl}>
                <InputItem
                  value={employee.note || ''}
                  valuChange={(val) => this.changeNote(val)}
                  style={styles.formControlText}
                  placeholder={i18n.t('employees.modal.employee.field.note.placeholder')}
                />
              </View>
            </View>
          </View>
        </View>
      </View>
    );
  }
};

/* StyleSheet =============================================================== */

const styles = StyleSheet.create({
  modalView: {
    position: 'absolute',
    left: 0,
    bottom: 0,
    right: 0,
    top: 0,
    alignItems: 'flex-start',
    backgroundColor: 'rgba(0,0,0,0.8)',
    flexDirection: 'row',
    paddingHorizontal: scaleSize(100),
    paddingVertical: scaleSize(30),
  },
  modalContainer: {
    flex: 1,
    backgroundColor: '#fff',
    overflow: 'hidden',
    borderRadius: scaleSize(15),
  },
  modalHeader: {
    backgroundColor: 'whitesmoke',
    height: scaleSize(90),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: scaleSize(30),
  },
  modalHeaderTitle: {
    color: '#000',
    fontSize: scaleSize(30),
  },
  modalHeaderButton: {
  },
  modalHeaderButtonLabel: {
    color: 'steelblue',
    fontSize: scaleSize(30),
  },
  modalBody: {
    paddingHorizontal: scaleSize(100),
    paddingTop: scaleSize(30),
    paddingBottom: scaleSize(50),
  },
  formGroup: {
    flexDirection: 'row',
  },
  formLabelText: {
    color: '#000',
    fontSize: scaleSize(30),
    textAlign: 'center',
  },
  formControl: {
    padding: scaleSize(20),
    height: scaleSize(90),
    marginVertical: scaleSize(10),
    borderWidth: scaleSize(1),
    borderColor: 'lightgrey',
    flex: 1,
    marginRight: scaleSize(50),
  },
  formControlText: {
    color: '#000',
  },
  inlineFormGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    flex: 1,
  },
});

export default EmployeeModal;